package com.tpsix.util;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.experimental.Accessors;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

@Getter
@Setter
@ApiModel("接口响应对象")
public class R<T> implements Serializable {

    private static final long serialVersionUID = -8552482278502200693L;

    private static final String SUCCESSFUL_MESSAGE = "successful";
    private static final int SUCCESSFUL_CODE = 200;

    @ApiModelProperty("状态码")
    private int code = SUCCESSFUL_CODE;

    @ApiModelProperty("描述")
    private String message;

    @ApiModelProperty("数据")
    private T data;

    public static R<Void> ok() {
        R<Void> r = new R<>();
        r.setMessage(SUCCESSFUL_MESSAGE);
        return r;
    }

    public static <T> R<T> ok(T data) {
        R<T> r = new R<>();
        r.setMessage(SUCCESSFUL_MESSAGE);
        r.setData(data);
        return r;
    }

    public static R<Void> error(String msg) {
        return error(HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);
    }

    public static R<Void> error(int code, String message) {
        R<Void> r = new R<>();
        r.setCode(code);
        r.setMessage(message);
        return r;
    }

    @SneakyThrows
    public static void responseWrite(HttpServletResponse response, String json, int status) {
        response.setStatus(status);
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }

}
